<?php
session_start();
//if (!isset($_SESSION["level"])) header("location:login.php");

include 'config.php';
include 'db_connection.php';

if (isset($_POST['id'])) {
//    showRequests();
}
if(isset($_POST['Login'])) {
  loginUser();
}
if(isset($_POST['submit_new_user'])) {
  createUser();
}

if (isset($_POST['event'])) {
  editReminder();
}

if (isset($_POST['event_id'])) {
    deleteReminder();
}

if (isset($_POST['parent_id'])) {
  deleteAllReminders();
}

if (isset($_POST['submit_new_reminder'])) {
  addReminder2();
}

if (isset($_POST['submit_change_pass'])) {
  changePassword();
}

if (isset($_POST['sendmail'])) {
  checkSpam();
}

if (isset($_POST['update_user'])){
    updateUser();
}


function showFilters($statuses) {
  $med_unit = mysql_query("SELECT DISTINCT med_unit FROM REQUESTS");
  $doc_name = mysql_query("SELECT DISTINCT doc_name FROM REQUESTS");
  $date_received = mysql_query("SELECT DISTINCT date_received FROM REQUESTS");
  $date_approved= mysql_query("SELECT DISTINCT date_approved FROM REQUESTS");
  $status = mysql_query("SELECT DISTINCT status FROM REQUESTS");

//   $med_unit = unitRename($unit);
  echo "<table id=\"filters\">
	<th><b>Επιλέξτε φίλτρο</b></th>";
  if ($_SESSION['level'] == "admin" || $_SESSION['level'] == "user") {
  echo	    "<tr><td>Μονάδα:</td>";
	    while ($rows=mysql_fetch_array($med_unit)){
	      echo "<td id=\"$rows[0]\" class=\"filter\"><a href=\"showrequest.php?req=$statuses&filter=$rows[0]\">";
	      echo $rows[0];
	      echo "</a></td>";
	    }
  echo "</tr>";
  }//end of if
  echo	  "<!--<tr class=\"datacelltwo\">
	    <td>Ιατρός:</td>
	      <td><select style=\"width: 100px;\">
		<option>Επιλέξτε...</option>";
		while ($rows=mysql_fetch_array($doc_name)){
		  echo "<option value=\"$rows[0]\" class=\"filter\">$rows[0]</option>\n";
		}
  echo " </select></td></tr>
	  <tr class=\"datacellone\">
	    <td>Ημερ/νία Παραλαβής:</td>
	  </tr>
	  <tr class=\"datacelltwo\">
	    <td>Ημερ/νία Έγκρισης:</td>
	  </tr> -->
	  <tr>
	    <td>Κατάσταση:";
	    while ($rows=mysql_fetch_array($status)){
	      echo "<td id=\"$rows[0]\" class=\"filter\"><a href=\"showrequest.php?req=$rows[0]\">";
	      echo $rows[0];
	      echo "</a></td>";
	    } 
  echo "</td>
	  </tr>

      </table>";
}

function addReminder() {
  if ( !isset($_SESSION["level"])) return;
  //if ($_POST['submit_new_reminder']) {
    $userID = $_SESSION['u_id'];
    $reminder_title = $_POST['title'];
    $start_date = $_POST['start_date'];
    $repeatition = $_POST['repeatition'];
    $start_time =$_POST['start_hours']  . ":" . $_POST['start_mins'] . ":" . "00";
    $end_date = $_POST['end_date'];
    $end_time = $_POST['end_hours'] . ":" . $_POST['end_mins'] . ":" . "00";
    $location = $_POST['location'];
    $description = $_POST['description'];

//echo $userID, $end_date, $end_time;
   $query = mysql_query("INSERT INTO REMINDERS (u_id, title, start_date, start_time, end_date, end_time, location, description, repeatition)
 			              VALUES ('$userID', '$reminder_title', '$start_date+$start_time', '$start_time', '$end_date+$end_time', '$end_time', '$location', '$description', '$repeatition')");

    if (!$query) {
      die('Invalid INSERT query: ' . mysql_error());
    }
    else {
        print("<script type = text/javascript>
	    alert (\"The remind has been succesfully created.\");
	    window.location.href = \"calendar.php\";</script>");
    } // end of else
  //}//end of if
}//end of addReminder

function addReminder2() {
    $userID = $_SESSION['u_id'];
    $title = $_POST['title'];
    $start_date = $_POST['start_date'];
    $start_hours = $_POST['start_hours'];
    $start_mins = $_POST['start_mins'];
    $start_time = $start_hours . ":" . $start_mins;
    $end_hours = $_POST['end_hours'];
    $end_mins = $_POST['end_mins'];
    $end_time = $end_hours . ":" . $end_mins;
    $weekday = date('N', strtotime($start_date));
    $location = $_POST['location'];
    $description = $_POST['description'];
    $start = $start_date . " " . $start_time;
    $end = $start_date . " " . $end_time;
    $month = date('m', strtotime($start_date));
    $day = date('d', strtotime($start_date));

    if (!isset($_POST['repeats'])) {
        $repeats = 0;
        $repeat_freq = 0;
        $query = mysql_query("INSERT INTO REMINDERS (u_id, title, start_date, start_time, end_time, weekday, repeats, repeats_freq, location, description)
 			              VALUES ('$userID', '$title', '$start_date', '$start_time', '$end_time', '$weekday', '$repeats', '$repeat_freq', '$location', '$description')");

        if (! $query) {  die('Invalid INSERT query: ' . mysql_error()); }

        $temp = mysql_query("SELECT parent_id FROM REMINDERS ORDER BY parent_id DESC LIMIT 1");
        $array = mysql_fetch_row($temp);
        $parent_id = $array[0];

        $query2 = mysql_query("INSERT INTO REMINDERS_RECURRANCY (parent_id, u_id, title, start, end)
 			              VALUES ('$parent_id', '$userID', '$title', '$start', '$end')");

        if (! $query2) {
            die('Invalid INSERT query2: ' . mysql_error());
            print("<script type = text/javascript>
            alert (\"Sorry, something went wrong! The remind has not been created.\");
            window.location.href = \"calendar.php\";</script>");
        }
    }
    else {
        $repeats = $_POST['repeats'];
        $repeat_freq = $_POST['repeats-freq'];
        $until = (18260/$repeat_freq); // 50 years from now, including leap years
        if ($repeat_freq == 1) {
            $weekday = 0;
            $freq = 1;
        }
        else if ($repeat_freq == 7) {
            $freq = 7;
        }
        else if ($repeat_freq == 30) {
            $freq = 30;
        }
        else if ($repeat_freq == 365) {
            $freq = 365;
        }

        $query = mysql_query("INSERT INTO REMINDERS (u_id, title,start_date, start_time, end_time, weekday, repeats, repeats_freq, location, description)
                VALUES ('$userID', '$title', '$start_date', '$start_time', '$end_time', '$weekday', '$repeats', '$freq', '$location', '$description')");

        if (! $query) {  die('Invalid INSERT query: ' . mysql_error()); }

        $temp = mysql_query("SELECT parent_id FROM REMINDERS ORDER BY parent_id DESC LIMIT 1");
        $array = mysql_fetch_row($temp);
        $parent_id = $array[0];

        for($x = 0; $x < $until; $x++) {
            if ($repeat_freq == 30) {
                $year = date('y', strtotime($start));
                $month = date('m', strtotime($start));

                switch ($month) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        $freq = 31;
                        break;
                    case 2:
                        if ($year % 4 == 0) { // leap year
                            $freq = 29;
                        }
                        else {
                            $freq = 28;
                        }
                        break;
                    default:
                        $freq = 30;
                }// end of switch
            } //end of if
            $query2 = mysql_query("INSERT INTO REMINDERS_RECURRANCY
                    (title, start, end, parent_id, u_id)
                    VALUES ('$title', '$start', '$end', '$parent_id', '$userID')");
            $start_date = strtotime($start . '+' . $freq . 'DAYS');
            $end_date = strtotime($end . '+' . $freq . 'DAYS');
            $start = date("Y-m-d H:i", $start_date);
            $end = date("Y-m-d H:i", $end_date);

            if (!$query2) {
                die('Invalid INSERT query: ' . mysql_error());
                print("<script type = text/javascript>
                alert (\"Sorry, something went wrong! The remind has not been created.\");
                window.location.href = \"calendar.php\";</script>");
            }// end of if
        }// end of for
    }
    print("<script type = text/javascript>
            alert (\"The remind has been succesfully created.\");
            window.location.href = \"calendar.php\";</script>");

}

function editReminder() {
  if ( !$_SESSION["user"] ) return;
//  /if ($_POST['event']) {
    $u_id = $_SESSION['u_id'];
    $event_id = $_POST['event'];
    $parent_id = $_POST['parent_ID'];
    $title = $_POST['title'];
    $start_date = $_POST['start_date'];
    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];
    $location = $_POST['location'];
    $description = $_POST['description'];
    $repeats = $_POST['repeats'];
    $repeats_freq = $_POST['repeats_freq'];
    $start = $start_date . " " . $start_time;
    $end = $start_date . " " . $end_time;

    //---------------------------------------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------------------

    // non recurring event
    if ($repeats_freq == 0) {
        $repeat_freq = 0;
       $query = mysql_query("UPDATE REMINDERS SET
          title = '$title',
          start_date='$start_date',
          start_time='$start_time',
          end_time='$end_time',
          location = '$location',
          description = '$description'
          WHERE parent_id='$parent_id' AND u_id='$u_id';");

        if (! $query) {  die('Invalid UPDATE query: ' . mysql_error()); }

        $temp = mysql_query("SELECT parent_id FROM REMINDERS ORDER BY parent_id DESC LIMIT 1");
        $array = mysql_fetch_row($temp);
        $parent_id = $array[0];

        $query2 = mysql_query("UPDATE REMINDERS_RECURRANCY SET
          title = '$title',
          start = '$start',
          end = '$end'
          WHERE parent_id = '$parent_id' AND u_id = '$u_id';");

        if (! $query2) {
            die('Invalid INSERT query2: ' . mysql_error());
        }
    }
    // recurring event
    else {
        if ($repeats_freq == 1) {
            $weekday = 0;
            $freq = 1;
        }
        else if ($repeats_freq == 7) {
            $freq = 7;
        }
        else if ($repeats_freq == 30) {
            $freq = 30;
        }
        else if ($repeats_freq == 365) {
            $freq = 365;
        }

        $query = mysql_query("UPDATE REMINDERS SET
              u_id = '$u_id',
              title = '$title',
              start_date = '$start_date',
              start_time = '$start_time',
              end_time = '$end_time',
              weekday = '$weekday',
              location = '$location',
              description = '$description',
              repeats_freq = '$repeats_freq'
              WHERE parent_id = '$parent_id' AND u_id = '$u_id';");

        if (! $query) {  die('Invalid UPDATE query: ' . mysql_error()); }


        $query2 = mysql_query("SELECT event_id FROM REMINDERS_RECURRANCY WHERE parent_id = '$parent_id';");

        while ($rows = mysql_fetch_row($query2)) {
            $event_ID = $rows[0];
            if ($repeats_freq == 30) {
                $year = date('y', strtotime($start));
                $month = date('m', strtotime($start));

                switch ($month) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        $freq = 31;
                        break;
                    case 2:
                        if ($year % 4 == 0) { // leap year
                            $freq = 29;
                        }
                        else {
                            $freq = 28;
                        }
                        break;
                    default:
                        $freq = 30;
                }// end of switch
            } //end of if
echo $start;
            $query3 = mysql_query("UPDATE REMINDERS_RECURRANCY SET
              title = '$title',
              start = '$start',
              end = '$end'
              WHERE event_id = '$event_ID' AND u_id = '$u_id';");

            $start_date = strtotime($start . '+' . $freq . 'DAYS');
            $end_date = strtotime($end . '+' . $freq . 'DAYS');
            $start = date("Y-m-d H:i", $start_date);
            $end = date("Y-m-d H:i", $end_date);
        }// end of while
    }
} // end of editReminder

function deleteReminder() {
  if ( ! $_SESSION['user'] ) return;
    $parent_id = $_POST['parent_id'];
    $event_id = $_POST['event_id'];
    $u_id = $_SESSION['u_id'];
    $repeats = $_SESSION['repeats'];

    $query = mysql_query("DELETE FROM REMINDERS_RECURRANCY WHERE event_id='$event_id' AND u_id='$u_id'");
    if (!$query) {
        die('Invalid DELETE query: ' . mysql_error());
    }
    if ($repeats == 0)  {
       $query2 = mysql_query("DELETE FROM REMINDERS WHERE parent_id= '$parent_id' AND u_id='$u_id'");
       if (!$query2) {
            die('Invalid DELETE query: ' . mysql_error());
       }
    }
}// end of deleteRequest

function deleteAllReminders() {
  if ( !$_SESSION["user"] ) return;
  $parent_id = $_POST['parent_id'];
  $u_id = $_SESSION['u_id'];

  $query = mysql_query("DELETE FROM REMINDERS WHERE parent_id= '$parent_id' AND u_id='$u_id'");
  if (!$query) {
    die('Invalid DELETE query: ' . mysql_error());
  }
    $query2 = mysql_query("DELETE FROM REMINDERS_RECURRANCY WHERE parent_id= '$parent_id' AND u_id='$u_id'");
    if (!$query2) {
        die('Invalid DELETE query: ' . mysql_error());
    }
 }


function showReminder($userID, $event_id) {

    $query = mysql_query("SELECT parent_id, start, end FROM REMINDERS_RECURRANCY WHERE u_id = '$userID' and event_id = '$event_id'");
    if (!$query) {
        die('Invalid SELECT query: ' . mysql_error());
    }

    $event = mysql_fetch_assoc($query);
    $parent_id = $event['parent_id'];
    $start = explode(" ", $event['start']);
    $start_date = $start[0];
    $start_time = $start[1];
    $end = explode(" ", $event['end']);
    $end_time = $end[1];

    $query2 = mysql_query("SELECT * FROM REMINDERS WHERE parent_id = '$parent_id'");
    if (!$query2) {
        die('Invalid SELECT query: ' . mysql_error());
    }

    $event_data = mysql_fetch_assoc($query2);

    echo '
        <table>
            <tr>
                <td>Title: <td>' . $event_data['title'] . '
            </tr>
            <tr>
                <td>Date: <td>' . $start_date . '
            </tr>
            <tr>
                <td>Start time: <td>' . $start_time . '
            </tr>
            <tr>
                <td>End time: <td>' . $end_time . '
            </tr>
            <tr>
                <td>Location: <td>' . $event_data['location'] . '
            </tr>
            <tr>
                <td>Description: <td>' . $event_data['description'] . '
            </tr>
            <tr>';
    if ($event_data['repeats'] == 0 ) {
        echo '<td>Repeats every: <td>Once';
    }
    else {
        echo '<td>Repeats every: <td>' . $event_data['repeats_freq'] . ' days';
    }

    echo '
            </tr>
        </table>
    ';

}//end of showReminder

  function loginUser() {
    $current_user = htmlspecialchars($_POST['username']);
    $current_pass = $_POST['password'];
    $current_pass_enc = sha1($current_pass);
    $query = mysql_query("SELECT u_id, level, email, phone FROM USERS WHERE username = '$current_user' AND password = '$current_pass_enc'");
    $count = mysql_num_rows($query);
    $row = mysql_fetch_row($query);

//echo $current_pass, $current_user, $count;

    if ($count == 1) {
      $_SESSION["user"] = $current_user;
      $_SESSION["pass"] = $current_pass_enc;
      $_SESSION["u_id"] = $row[0];
      $_SESSION["level"] = $row[1];
      $_SESSION["mail"] = $row[2];
      $_SESSION["phone"] = $row[3];
        print_r($row);
//       $_SESSION["level"] = mysql_result($query, 0);
//       $_SESSION["department"] = mysql_result($query, 1);

    if ($_SESSION["level"] == "admin")
	    header("location:index.php");
    else
	    header("location:index.php");
    }//end of if

    else {
    ?>
    <script type = text/javascript>
      alert ("Sorry, I couldn't validate your username/password.");
      window.location.href = "login.php";
    </script>
    <?php
    }//end of else
  }//end of loginUser

function createUser() {
  $new_user = htmlspecialchars($_POST['username']);
  $new_pass = $_POST['password'];
  $new_pass_enc = sha1($new_pass);
  $email = $_POST['email'];
  $phone_number = $_POST['phone_number'];
  $level = "user";
  $query = mysql_query("SELECT username FROM USERS WHERE username = '$new_user'");
  $count = mysql_num_rows($query);

  if ($count != 0) {
    print("<script type = text/javascript>
	    alert (\"Sorry, This username is already taken.\");
	    window.location.href = \"createuser.php\";
	  </script>");
    //header("location:createuser.php");
  }
  else {
    $query = mysql_query("INSERT INTO USERS (username, password, email, phone, level)
			  VALUES ('$new_user', '$new_pass_enc', '$email', '$phone_number', '$level');");
    if (!$query) {
      die('Invalid INSERT query: ' . mysql_error());
    }
    else {
      print("<script type = text/javascript>
	    alert (\"The account has succesfully been created.\");
	    window.location.href = \"createuser.php\";</script>");
    //header("location:createuser.php");
    }// end of else
  }//end of outer else
}//end of createuser

function updateUser() {
    $username = $_POST['username'];
    $password = sha1($_POST['password']);
    $new_password = $_POST['new_password'];
    $password_confirm = $_POST['password_confirm'];
    $enc_password_confirm = sha1($_POST['password_confirm']);
    $email = $_POST['email'];
    $phone_number = $_POST['phone_number'];

    if ($username == $_SESSION['user'] || $_SESSION['level'] == "admin") {
        $check = mysql_query("SELECT username FROM USERS WHERE password='$password' AND username='$username'");
        $count = mysql_num_rows($check);
        if ($count == 1) {
            $query = mysql_query("UPDATE USERS SET password='$enc_password_confirm', email='$email', phone='$phone_number' WHERE username='$username'");
            if (!$query) {
                die('Invalid INSERT query: ' . mysql_error());
            }
            else {
                print("<script type = text/javascript>
	            alert (\"The password has been succesfully changed.\");
	            window.location.href = \"update_user.php\";</script>");
            }// end of else
        }//end of if
        else {
            print("<script type = text/javascript>
	         alert (\"The current password you entered is wrong.\");
	        window.location.href = \"update_user.php\";</script>");
        }
    }//end of if
    else {
        print("<script type = text/javascript>
	      alert (\"You don't have the permission to change this user's password.\");
	      window.location.href = \"index.php\";</script>");
    }
}//end of updateUser

function changePassword() {
  $current_password = $_POST['current_password'];
  $current_password_enc = sha1($current_password);
  $new_password = $_POST['new_password'];
  $enc_password = sha1($new_password);
  $user = $_POST["username"];
  if ($user == $_SESSION['user'] || $_SESSION['level'] == "admin") {
    $check = mysql_query("SELECT username FROM USERS WHERE password='$current_password_enc' AND username='$user'");
    $count = mysql_num_rows($check);
    if ($count == 1) {
      $query = mysql_query("UPDATE USERS SET password='$enc_password' WHERE username='$user'");

      if (!$query) {
	    die('Invalid INSERT query: ' . mysql_error());
      }
      else {
	print("<script type = text/javascript>
	      alert (\"The password has been succesfully changed.\");
	      window.location.href = \"changepassword.php\";</script>");
      }// end of else
    }//end of if
    else {
	print("<script type = text/javascript>
	      alert (\"The current password you entered is wrong.\");
	      window.location.href = \"changepassword.php\";</script>");
    }
  }//end of if
  else {
	print("<script type = text/javascript>
	      alert (\"You don't have the permission to change this user's password.\");
	      window.location.href = \"changepassword.php\";</script>");  
  }
}// end changePassword


function mailReminder() {
  $to = $_SESSION["mail"];
  $from = "irtsoup@gmail.com";
  $subject = $_POST['subject'];
  $message = $_POST['message'];
   
  mail($to, "Subject: $subject", $message, "From: $from" );
  header("location:contact.php");  

}// end of mailReminder



function showLeftPanel($level, $user) {
print("<div id=\"menu\" class=\"curvy1\"> 
     <ul class=\"level1\">
	  <li><a href=\"index.php\">Home</a></li>");
	if ($level == "admin") {
	  print("
        <li><a href=\"calendar.php\">My Calendar</a></li>
        <li><a href=\"insert_reminder.php\">Insert Reminder</a></li>
        <li><a href=\"update_user.php\">My Settings</a></li>
        <li><a href=\"#\">Administer</a>
		  <ul>
		    <li><a href=\"createuser.php\">Create User</a></li>
		    <li><a href=\"user_settings.php\">User Settings</a></li>
		  </ul>
		</li>");
	}
    else if ($level == "user"){
        print('
        <li><a href="calendar.php">My Calendar</a></li>
        <li><a href="insert_reminder.php">Insert Reminder</a></li>
        <li><a href="update_user.php">My Settings</a></li>');
    }
    else if ($level == "") {
        print ("<li><a href=\"create_account.php\">Create account</a></li>");
    }
	print("<li><a href=\"contact.php\">Contact</a></li>");
	if ( $level == "") { 
	  print("<li><a class=\"fly\" href=\"./login.php\">Login</a>");
	}
	else {
	  print("<li><a class=\"fly\" href=\"./logout.php\">Logout</a>");
	}
        print("</ul></div><!--END of menu-->");
}

function showRightPanel() {
  if (isset($_SESSION["user"])) {
    $user = $_SESSION["user"];
    if ($_SESSION["level"] == "admin") {
      echo "<p>Γεια χαρά, $user !</p>";
      //echo "<p><a href=\"./admin.php\">Administer</a></p>";
      echo "<p><a href=\"./logout.php\">Logout</a></p>";
    } 
    else { 
      echo "<p>Γεια χαρά, $user !</p>";
      echo "<p><a href=\"./logout.php\">Αποσύνδεση</a></p>";
    }
  }
  else {
      echo "<p>Γεια χαρά, φίλε !</p>";
      echo "<p><a href=\"./login.php\">Είσοδος</a></p>";
      echo "<p><a href=\"./create_account.php\">Δημιουργία Λογαριασμού</a></p>";
  }
}// end of showRightPanel

function showFooter() {
echo "
  <div id=\"footer_div\">
    <p>Designed, developed and maintained 
    <p>by Iraklis Tsoupouroglou
  </div>";
} // end of showFooter

//
function showMenu() {
    print('<div id="menu">
    <table>
        <tr>
            <td><a href="index.php">Home</a></td>');
    if (!isset($_SESSION['user'])) {
     print('<td><a href="create_account.php">Create Account</a></td>
            <td><a href="login.php">Login</a></td>');
    }// end of if
    else {
        print('
            <td><a href="calendar.php">My Calendar</a></td>
            <td><a href="insert_reminder.php">Insert Reminder</a></td>
            <td><a href="update_user.php">My Settings</a></td>');
    }
    print('<td><a href="">Contact</a></td>
        </tr>
    </table>
</div>');
}

function drawCalendar($month,$year){
    echo "<h2>" . date('F') . " " . $year . "</h2>\n";
    /* draw table */
    $calendar = '<table cellpadding="0" cellspacing="0" class="calendar">' . "\n";

    /* table headings */
    $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    $calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>' . "\n";

    /* days and weeks vars now ... */
    $running_day = date('w',mktime(0,0,0,$month,1,$year));
    $days_in_month = date('t',mktime(0,0,0,$month,1,$year));
    $days_in_this_week = 1;
    $day_counter = 0;
    $dates_array = array();

    /* row for week one */
    $calendar.= '<tr class="calendar-row">';

    /* print "blank" days until the first of the current week */
    for($x = 0; $x < $running_day; $x++) {
        $calendar.= '<td class="calendar-day-np"> </td>';
        $days_in_this_week++;
    }

    /* keep going with days.... */
    for($list_day = 1; $list_day <= $days_in_month; $list_day++) {
        $calendar.= '<td class="calendar-day" id="' . $list_day . '-' . $month . '-' . $year . '">';
        /* add in the day number */
        $calendar.= '<div class="day-number">'.$list_day.'</div>';

        /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
        //$calendar.= str_repeat('<p> </p>',2);

        $calendar.= '</td>';
        if($running_day == 6) {
            $calendar.= '</tr>' . "\n";
            if(($day_counter+1) != $days_in_month) {
                $calendar.= '<tr class="calendar-row">';
            }
            $running_day = -1;
            $days_in_this_week = 0;
        }
        $days_in_this_week++; $running_day++; $day_counter++;
    }

    /* finish the rest of the days in the week */
    if($days_in_this_week < 8){
        for($x = 1; $x <= (8 - $days_in_this_week); $x++) {
            $calendar.= '<td class="calendar-day-np"> </td>';
        }
    }

    /* final row */
    $calendar.= '</tr>' . "\n";

    /* end the table */
    $calendar.= '</table>' . "\n";

    /* all done, return result */
    return $calendar;
}// end of drawCalendar